package com.bawei.mall.product.service.impl;

import com.alibaba.fastjson2.JSON;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.product.domain.MallProductLove;
import com.bawei.mall.product.mapper.MallProductMapper;
import com.bawei.mall.product.service.MallProductLoveServie;
import com.bawei.mall.user.domain.CusUser;
import com.bawei.system.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MallProductLoveServieImpl implements MallProductLoveServie {
    @Autowired
    private MallProductMapper mallProductMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;


    private static final String ACCESS_TOKEN="login_tokens:";

    @Override
    public void addLove(MallProductLove mallProductLove) {
//        Integer brandId = mallProductLove.getBrandId();
//        MallProductLove list = mallProductMapper.selectList(brandId);

        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String tokenKey = getTokenKey(key);
        String s = redisTemplate.opsForValue().get(tokenKey);
        LoginUser loginUser = JSON.parseObject(s, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        mallProductLove.setUserId(Integer.valueOf(String.valueOf(cusUser.getUserId())));
        Integer userId = cusUser.getUserId();
        Integer brandId = mallProductLove.getBrandId();
        MallProductLove list = mallProductMapper.selectList(brandId,userId);
        if(list!=null){
            throw new RuntimeException("已经收藏");
        }
        mallProductMapper.addLove(mallProductLove);
    }

    @Override
    public void del(Integer id) {
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String tokenKey = getTokenKey(key);
        String s = redisTemplate.opsForValue().get(tokenKey);
        LoginUser loginUser = JSON.parseObject(s, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        Integer userId = cusUser.getUserId();
        mallProductMapper.del(id,userId);
    }

    private String getTokenKey(String key) {
        return ACCESS_TOKEN + key;
    }
}
